<template>
  <div class="min-h-screen bg-gray-200">
    <!--导航部分-->
    <ShopHomeHeader @cat-update="(n)=>dialogVisible=n" @changeNavTab="(n) => activeNavTab =n"  :activeNavTab="activeNavTab" />
    <!-- <ShopHomeHeader @cat-update="(n)=>dialogVisible=n" v-model="activeNavTab" /> -->
    <!-- 主题部分 -->
    <div class="container mx-auto px-4 mb-6 md:px-8">
      <div class="bg-white ">
        <div class="bg-white h-1"></div>
        <!-- 产品分类 -->

        <div class="bg-gray-100 px-2 pt-4 ml-4 mt-4 flex items-center gap-4 rounded-sm" v-if="activeNavTab =='商家首页'">
          <template v-for="(item, index) in tabs">
            <button :class="[
              'px-2 py-1 text-base ',
              activeTab === index
                ? 'text-red-600 border-b-2 border-red-600 font-bold text-xm'
                : 'text-gray-600 font-medium',
            ]" @click="activeTab = index">
              {{ item.text }}
              <span v-if="item.count" class="px-1 rounded bg-red-600 text-white">{{ item.count }}</span>
            </button>
          </template>
        </div>
        <!-- 搜索本店 -->
        <!-- 搜索与操作区域 -->
        <div class="flex items-center justify-between space-x-4 py-4 mx-4">
          <div class="flex items-center space-x-4">
            <!-- 搜索框 -->
            <div class="flex items-center">
              <el-input placeholder="输入关键字" class="w-full rounded-l border-2 border-red-500" prefix-icon="Search"
                size="small" />
              <button class="bg-[#f04848] p-0.5 text-white !rounded-button whitespace-nowrap">
                <span class="font-bold">搜本店</span>
              </button>
            </div>
            <!-- 排序选项 -->
            <div class="flex space-x-8">
              <button class="text-[#ff6600] font-bold">综合</button>
              <button class="flex items-center space-x-1 text-gray-600 hover:text-[#ff6600] hover:font-bold"
                @click="handlePriceSort">
                <span>价格</span>
                <div class="flex flex-col ">
                  <el-icon style="height: 0.5em;">
                    <CaretTop />
                  </el-icon>
                  <el-icon style="height: 0.5em;">
                    <CaretBottom />
                  </el-icon>
                </div>
              </button>
              <button class="flex items-center space-x-1 text-gray-600 hover:text-[#ff6600] hover:font-bold">
                <span>人气</span>
                <el-icon size="large">
                  <DCaret />
                </el-icon>
              </button>
              <button class="flex items-center space-x-1 text-gray-600 hover:text-[#ff6600] hover:font-bold">
                <span>时间</span>
                <el-icon size="large">
                  <DCaret />
                </el-icon>
              </button>
            </div>
          </div>
          <!-- 联系商家 -->
          <div class="flex items-center space-x-2">
            <span class="text-gray-600">联系商家</span>
            <img src="/src/assets/image/qq-chat.gif" alt="商家qq" />
          </div>
        </div>
        <!-- 商品列表 -->
        <div class="container mx-auto px-4 ">
          <div class="grid grid-cols-5 gap-6">
            <div v-for="(product, index) in products" :key="index"
              class="bg-white rounded-lg shadow-sm overflow-hidden">
              <div class="relative">
                <a :href="`/productDetails/${product.id}`" target="_blank">
                  <!-- <div class="groom" v-if="product.recommend"></div> -->
                  <img :src="product.image" :alt="product.name" class="w-full aspect-square object-cover" />
                </a>
                <span v-if="product.tag" class="absolute top-2 right-2 px-2 py-1 text-xs text-white rounded"
                  :class="product.tagClass">
                  {{ product.tag }}
                </span>
              </div>
              <!-- 商品的描述 -->
              <div class="">
                <a href="#" target="_blank">
                  <!-- <h3 class="text-sm text-gray-800">{{ product.name }}</h3> -->
                  <p class="text-gray-400 text-xs mb-2 mt-1 mx-1">
                    {{ product.description }}
                  </p>
                </a>
                <div class="mt-2 mx-1 flex items-center justify-between">
                  <span class="text-orange-500 text-lg font-medium">¥{{ product.price }}</span>
                  <div class="price-tag flex items-center">
                    <button class="ml-0.5 text-sm text-sky-400 rounded border border-sky-300 px-1"
                      @click="addToFavorites(product.id)">
                      收藏
                    </button>
                  </div>
                </div>

                <div class="flex items-center justify-between p-2 space-x-2 border-t mt-1 border-gray-200">
                  <span>货号: {{ product.itemNumber }}</span>
                  <span class="text-sm">更新: {{ product.updateTime }}</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="mt-8 flex">
            <el-pagination hide-on-single-page v-model:current-page="currentPage" :page-size="20" :total="pageTotal"
              prev-text="上一页" next-text="下一页" layout="prev, pager, next,total,jumper"
              @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <Footer2 />
    </div>
  </div>

  <!-- 商家动态的弹窗 -->
  <el-dialog title="商家动态信息" v-model="dialogVisible" class="overflow-hidden">
    <div class="max-h-96 overflow-y-auto p-4 space-y-4">
      <div v-for="(item, index) in dynamicList" :key="index" class="p-2 bg-white rounded border-b border-gray-200">
        <div v-if="item.type === 'price'">
          商品拿货价格变动厂商:{{ item.manufacturer }} 货号:
          {{ item.sku }} 原价: {{ item.originalPrice }} 现价:
          {{ item.currentPrice }}
        </div>
        <div v-else-if="item.type === 'skuPrice'">
          sku价格变动, 厂商: {{ item.manufacturer }} 货号: {{ item.sku }}
          <el-button type="primary" size="small" class="ml-2" @click="viewDetail(item)">
            查看详情
          </el-button>
        </div>
        <div v-else-if="item.type === 'status'">
          厂商:{{ item.manufacturer }};商品货号:{{ item.sku }}状态变更为{{
          item.status
          }}
        </div>
        <div class="text-sm text-gray-500 mt-2">
          {{ item.date }}来自更新日志!
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 查看详情 -->
  <el-dialog title="查看价格修改详情" v-model="dialogVisible2">
    <div class="mb-4">
      <p class="font-semibold">来源: 来自APP</p>
      <p class="font-semibold">货号: 996</p>
      <p class="font-semibold">厂家: 巨佳</p>
    </div>
    <el-table :data="tableData" class="w-full border" :span-method="objectSpanMethod">
      <el-table-column prop="color" label="颜色" width="80" class="border"></el-table-column>
      <el-table-column prop="size" label="尺码" width="60" class="border"></el-table-column>
      <el-table-column prop="oldPrice" label="原拿货价" class="border"></el-table-column>
      <el-table-column prop="newPrice" label="新拿货价" class="border"></el-table-column>
      <el-table-column prop="oldOrder" label="原订货价" class="border"></el-table-column>
      <el-table-column prop="newOrder" label="新订货价" class="border"></el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch ,onMounted} from "vue"
import ShopHomeHeader from "./ShopHomeHeader.vue"
import Footer2 from "@/components/Footer2.vue"
import { useRoute } from 'vue-router';
const route = useRoute();
//加载json模拟数据
import loadLocalJson from "@/https/local/localJson.js"
//活跃的导航
const activeNavTab = ref("商家首页")
//主页商品信息
const products = ref([])
// 分类标签
const tabs = ref([{ text: "所有产品" }])
// 当前选中标签
const activeTab = ref(0);
//获取商品信息
const getProductList = async () => {
//  获取商品列表 传递参数 {categoryId:activeTab.value,今日伤心，已下架，关键词，价格，人气，时间}
  const res = await loadLocalJson("json/merchant/productsAll.json").then((res) => {
    products.value = res.data
  })
}
onMounted(async () => {
  //获取商品分类数据
  await loadLocalJson("json/merchant/category.json").then((res) => {
    tabs.value = [...tabs.value, ...res.data];
  })
  console.log(route.params,'<<<params',route.query,'<<<query');
  const tag = route.query.tabType
  console.log(tag);
  if(tag=='new'){
    activeNavTab.value='今日上新'
  }else if(tag=='remove'){
    activeNavTab.value='已下架'
  }else if(tag=='stock'){
    console.log(111);
    activeNavTab.value='商家首页'
    console.log(activeNavTab.value,'111<<<activeNavTab.value');
  }
  console.log(activeNavTab.value,'<<<activeNavTab.value');
   //查看页面跳转的时候 是否有分类信息
   const { shopId } = route.params
  const { categoryId } = route.params
  console.log("shopId:",shopId, "categoryId:",categoryId);
  // console.log(tabs.value, 'tabs');
  const index =  tabs.value.findIndex(item=>item.id==categoryId)
  console.log(index,'index');
  if(index!=-1){
     activeTab.value = index
  }else{
    activeTab.value = 0
  }
    //获取商品列表 可以传递分类的信息 根据分类信息的不同查询数据
  getProductList()
 
})
const handlePriceSort=()=>{
  console.log('handlePriceSort');
}

//分页相关的数据
const currentPage = ref(1);
const pageTotal = ref(0);
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  //todo 做分页查询
};

// 模拟商家动态 数据（根据实际接口数据调整结构）
const dialogVisible = ref(false); // 控制弹框显示
const dynamicList = ref([]);
//todo  修改成调用真是接口的
const getDynamicList = async () => {
  await loadLocalJson("json/merchant/dynamicList.json").then((res) => {
    dynamicList.value =res.data;
    console.log(dynamicList.value,'111',res.data)
  })
};


watch(activeNavTab, async (newVal, oldVal) => {
  //todo根据条件查询
  console.log(newVal, oldVal);
  if (newVal =='商家动态') {
    getDynamicList();
  }
  if (newVal =='今日上新') {
    await loadLocalJson("json/merchant/productsNew.json").then((res) => {
      products.value = res.data
    })
  }
  if (newVal =='已下架') {
    await loadLocalJson("json/merchant/productsOld.json").then((res) => {
      products.value = res.data
    })
  }
  if (newVal =='商家首页') {
    getProductList()
   
  }
})
const dialogVisible2 = ref(false);

const tableData = ref([])
const  getDynamicTableData= async()=>{
  await loadLocalJson("json/merchant/dynamicTableData.json").then((res) => {
    tableData.value = res.data
    console.log(tableData.value,'222tableData')
  })
}
const viewDetail = (item) => {
  console.log("查看详情", item) // 可替换为实际跳转逻辑
  dialogVisible2.value = true
  getDynamicTableData()
};

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  // console.log(row, column, rowIndex, columnIndex);
  if (columnIndex === 0) {
    // Find all rows with the same color
    const sameColorRows = tableData.value.filter(item => item.color === row.color);
    // Find the first occurrence of this color
    const firstIndex = tableData.value.findIndex(item => item.color === row.color);
    // If this is the first row of this color group
    if (rowIndex === firstIndex) {
      return {
        rowspan: sameColorRows.length,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}
</script>
<style lang="less" scoped>
.el-table {
  border: 1px solid #e5e7eb;
  /* Tailwind border-gray-200 */
}

.el-table__header th,
.el-table__cell {
  border: 1px solid #e5e7eb;
}

</style>
